package com.weiwei.diancan.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.weiwei.diancan.Contant.ConfigMethod;
import com.weiwei.diancan.R;
import com.weiwei.diancan.adapter.HomeOpenAdapter;
import com.weiwei.diancan.adapter.MenuOpenAdapter;
import com.weiwei.diancan.base.BaseActivity;
import com.weiwei.diancan.bean.LoginBean;
import com.weiwei.diancan.bean.MenuBean;
import com.weiwei.diancan.bean.SelectOrder;
import com.weiwei.diancan.cache.CacheConfig;
import com.weiwei.diancan.http.RetrofitFactory;
import com.weiwei.diancan.utils.ActivityManager;
import com.weiwei.diancan.utils.LoggerUtils;
import com.weiwei.diancan.view.EmptyLayout;
import com.weiwei.diancan.view.SimpleSwipeRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import weiwei.com.weiweilibrary.views.ToastUtil;


public class OpenActivity extends BaseActivity {

    private TextView tv_has_order;
    private List<LoginBean.MenuListBean> menuListBean;
    private ListView lv_menu;
    private TextView tv_type_titile;
    private ListView lv_home;
    private MenuOpenAdapter menuAdapter;
    private HomeOpenAdapter homeAdapter;
    private List<String> data = new ArrayList<>();

    private ArrayList<SelectOrder> selectOrders = new ArrayList<>();

    /**
     * 里面存放右边ListView需要显示标题的条目position
     */
    private ArrayList<Integer> showTitle;

    private int currentItem;
    private ArrayList<MenuBean> menuBean;
    private EmptyLayout emptyLayout;
    private LoginBean.TypeListBean.TabListBean tabListBean;  //当前订单的餐桌信息
    private SimpleSwipeRefreshLayout refresh;
    private String num;

    private TextView tv_caipin;
    private TextView tv_shuliang;
    private TextView tv_jiage;
    private DecimalFormat df;

    @Override
    public void getData() {
        initData();

        lv_menu.setAdapter(menuAdapter);
        lv_home.setAdapter(homeAdapter);
        tv_type_titile.setText(menuListBean.get(0).getType_name());
    }



    /**
     * 刷新
     */
    private void onRefreshData(){
        if(TextUtils.isEmpty(CacheConfig.getInst().getToken(this))){
            ToastUtil.showToast(this,"没有登录！");
            refresh.setRefreshing(false);
            return;
        }

        if(TextUtils.isEmpty(CacheConfig.getInst().getWaterToken(this))){
            ToastUtil.showToast(this,"请绑定工号！");
            refresh.setRefreshing(false);
            return;
        }

        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        RetrofitFactory.getIntance().refreshData(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {
                        refresh.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        refresh.setRefreshing(false);
                        emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR,-1);
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        loginBean.setShop_token(CacheConfig.getInst().getToken(OpenActivity.this));
                        CacheConfig.getInst().putData(loginBean);
                        menuListBean = loginBean.getMenu_list();
                        menuAdapter.setData(loginBean.getMenu_list());
                        homeAdapter.setData(loginBean.getMenu_list());
                        initData();
                    }
                });
    }

    @Override
    public void setListeners() {
        /**
         * 刷新
         */
        refresh.setOnRefreshListener(() -> {
            onRefreshData();
        });

        tv_has_order.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("num",num);
            bundle.putSerializable("tabListBean",tabListBean);
            bundle.putParcelableArrayList("selectList",selectOrders);
            openActivity(HasOrderActivity.class,bundle);
        });

        homeAdapter.setOnItemClick(new HomeOpenAdapter.OnItemClick() {
            @Override
            public void onAdd(MenuBean menuBean, int pos, TextView textView) {

                boolean hasCount = false;

                LoginBean.MenuListBean.DishListBean dish = menuBean.getTabListBean();
                String log_type = dish.getLog_type();
                String id = null;
                if(log_type.equals("0")){
                    id = menuBean.getTabListBean().getDish_id();
                }else if(log_type.equals("1")){
                    id = menuBean.getTabListBean().getSet_id();
                }

                for(int i = 0;i<selectOrders.size();i++){
                    SelectOrder selectOrder = selectOrders.get(i);

                    if(id.equals(selectOrder.getData_id())){
                        int log_count = Integer.parseInt(selectOrder.getLog_count());
                        log_count++;
                        hasCount = true;
                        selectOrder.setLog_count(log_count+"");
                    }

                }

                if(!hasCount) {
                    if (log_type.equals("0")) {
                        SelectOrder selectOrder = new SelectOrder(log_type, dish.getDish_id(),
                                dish.getDish_name(), dish.getDish_price()
                                , textView.getText().toString(),dish.getDish_unit());
                        selectOrders.add(selectOrder);
                    } else if (log_type.equals("1")) {
                        SelectOrder selectOrder = new SelectOrder(log_type, dish.getSet_id(),
                                dish.getSet_name(), dish.getSet_price(),
                                textView.getText().toString(),dish.getSet_unit());
                        selectOrders.add(selectOrder);
                    }
                }


                tv_caipin.setText(selectOrders.size()+"");
                int num = 0;
                double price = 0;
                for(int i = 0;i<selectOrders.size();i++){
                    String log_count = selectOrders.get(i).getLog_count();
                    String log_price = selectOrders.get(i).getLog_price();

                    int i1 = Integer.parseInt(log_count);
                    double v = Double.parseDouble(log_price);
                    num+=i1;
                    price+=v*i1;
                }
                tv_shuliang.setText(num+"");
                tv_jiage.setText(df.format(price));

            }

            @Override
            public void onAjj(MenuBean menuBean, int pos, TextView textView) {

                String log_type = menuBean.getTabListBean().getLog_type();
                String id = null;
                if(log_type.equals("0")){
                    id = menuBean.getTabListBean().getDish_id();
                }else if(log_type.equals("1")){
                    id = menuBean.getTabListBean().getSet_id();
                }



                for(int i = 0;i<selectOrders.size();i++){
                    SelectOrder selectOrder = selectOrders.get(i);
                    if(id.equals(selectOrder.getData_id())){
                        String log_count = selectOrder.getLog_count();
                        int i1 = Integer.parseInt(log_count);

                        if(i1 == 1){
                            selectOrders.remove(selectOrder);
                        }else{
                            i1--;
                            selectOrder.setLog_count(i1+"");
                        }

                    }
                }

                double num = 0;
                double price = 0;
                for(int i = 0;i<selectOrders.size();i++){
                    String log_count = selectOrders.get(i).getLog_count();
                    String log_price = selectOrders.get(i).getLog_price();

                    double i1 = Double.parseDouble(log_count);
                    double v = Double.parseDouble(log_price);
                    num+=i1;
                    price+=v*i1;
                }

                tv_caipin.setText(selectOrders.size()+"");
                tv_shuliang.setText(num+"");
                if(price == 0){
                    tv_jiage.setText("¥0.00");
                }else {
                    tv_jiage.setText("¥"+df.format(price));
                }

            }

            @Override
            public void onAllClick(int pos) {
                LoginBean.MenuListBean.DishListBean tabListBean1 = menuBean.get(pos).getTabListBean();

                Bundle bundle = new Bundle();
                bundle.putSerializable("menu", tabListBean1);
                if(tabListBean1.getLog_type().equals("0")){ //单品
                    openActivity(DanpinActivity.class,bundle);
                }else if(tabListBean1.getLog_type().equals("1")){ //套餐
                    openActivity(ShangpinActivity.class,bundle);
                }
            }
        });

/**
 * 餐桌分类
 */
        lv_menu.setOnItemClickListener((arg0, arg1, arg2, arg3) -> {
            menuAdapter.setSelectItem(arg2);
            menuAdapter.notifyDataSetInvalidated();
            lv_home.setSelection(showTitle.get(arg2));

            tv_type_titile.setText(data.get(arg2));

        });
        lv_home.setOnScrollListener(new AbsListView.OnScrollListener() {
            private int scrollState;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub
                this.scrollState = scrollState;
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    return;
                }
                int current =showTitle.indexOf(firstVisibleItem );
//				lv_home.setSelection(current);
                if(currentItem != current && current >=0){
                    currentItem = current;
                    tv_type_titile.setText(data.get(current));
                    menuAdapter.setSelectItem(currentItem);
                    menuAdapter.notifyDataSetInvalidated();
                }
            }
        });




    }


    @Override
    public void initView() {
        df = new java.text.DecimalFormat("#.00");

        tv_caipin = (TextView) findViewById(R.id.tv_caipin);
        tv_shuliang = (TextView)findViewById(R.id.tv_shuliang);
        tv_jiage = (TextView)findViewById(R.id.tv_jiage);
        lv_menu = (ListView)findViewById(R.id.lv_menu);
        tv_type_titile = (TextView)findViewById(R.id.tv_type_titile);
        lv_home = (ListView)findViewById(R.id.lv_home);
        emptyLayout = (EmptyLayout)findViewById(R.id.emptyLayout);
        refresh = (SimpleSwipeRefreshLayout)findViewById(R.id.refresh);
        refresh.setViewGroup(lv_home);
        refresh.setColorSchemeColors(Color.parseColor("#B41B1B"));
        tv_has_order = (TextView)findViewById(R.id.tv_has_order);

        menuAdapter = new MenuOpenAdapter(this,menuListBean);
        homeAdapter = new HomeOpenAdapter(this, menuListBean);
    }

    @Override
    public void initTitle() {
        titler.setText("御膳府");

        iv_left.setVisibility(View.VISIBLE);
        iv_left.setText("返回");
        iv_left.setOnClickListener(v->finish());

        iv_right.setVisibility(View.VISIBLE);
        iv_right.setText("清除");
        iv_right.setOnClickListener(v->{
            selectOrders = new ArrayList<SelectOrder>();
            if(homeAdapter!=null){
                homeAdapter.clearSelect();
            }
            tv_jiage.setText("¥0.00");
            tv_shuliang.setText("0");
            tv_caipin.setText("0");
        });
    }



    @Override
    public void setLayoutView() {
        setContentView(R.layout.activity_open);
        ActivityManager.getInstance().pushOneActivity(this);
        Bundle extras = getIntent().getExtras();
        tabListBean = (LoginBean.TypeListBean.TabListBean)extras.getSerializable("tabListBean");
        num = extras.getString("num");
        menuListBean = CacheConfig.getInst().getLogin().getMenu_list();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().popOneActivity(this);
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEvent(String s){
        if(s.equals("diandan")){
            selectOrders = new ArrayList<SelectOrder>();
            if(homeAdapter!=null){
                homeAdapter.clearSelect();
            }
            tv_jiage.setText("¥0.00");
            tv_shuliang.setText("0");
            tv_caipin.setText("0");
        }else if(s.equals("zhuidan")){
            finish();
        }
    }

    public void initData(){
        if(menuListBean.size() == 0){
            emptyLayout.setErrorType(EmptyLayout.NO_DATA,EmptyLayout.NOT_DATA);
        }else{
            emptyLayout.setVisibility(View.GONE);
        }
        menuBean = new ArrayList<>();
        for(int i = 0;i<menuListBean.size();i++){
            List<LoginBean.MenuListBean.DishListBean> tab_list = menuListBean.get(i).getDish_list();
            data.add(menuListBean.get(i).getType_name());
            for(int j = 0;j<tab_list.size();j++){
                menuBean.add(new MenuBean(tab_list.get(j),menuListBean.get(i).getType_id(),menuListBean.get(i).getType_name()));
            }
        }


        showTitle = new ArrayList<Integer>();
        for(int i = 0; i < menuBean.size(); i++){
            if( i ==0){
                showTitle.add(i );
            }else if (!TextUtils.equals(menuBean.get(i).getTitle(), menuBean.get(i - 1).getTitle())) {
                showTitle.add(i );
            }
        }
    }
}
